<template>
    <el-dialog v-model="visible" title="新增母设备" width="90%">

    <el-button type="primary" @click="addDialog.open()">新增备件</el-button>
    <AddSpareDialog ref="addDialog" @refresh="loadData" />

      <!-- 系统选择 -->
      <el-form label-width="90px" class="mb12">
        <el-form-item label="系统" required>
          <el-cascader
            v-model="rootPath"
            :props="cProps"
            filterable
            clearable
            placeholder="请选择系统层节点"
            style="min-width: 400px"
            show-all-levels
            @change="onSystemSelect"
          >
            <template #default="{ node, data }">
              <div class="cas-opt">
                <span>{{ data.label }}</span>
                <el-tag size="small" type="success">系统</el-tag>
              </div>
            </template>
          </el-cascader>
        </el-form-item>
      </el-form>
  
      <!-- 表格部分 -->
      <el-divider content-position="left">母设备列表</el-divider>
  
      <div class="machine-table">
        <div class="table-header">
          <div class="col code">设备编码</div>
          <div class="col name">设备名称</div>
          <div class="col dept">归属部门</div>
          <div class="col area">区域</div>
          <div class="col spec">规格</div>
          <div class="col brand">品牌</div>
          <div class="col amount">金额(万)</div>
          <div class="col spares">备件信息</div>
          <div class="col ops">操作</div>
        </div>
  
        <div
          class="table-row"
          v-for="(m, i) in machines"
          :key="m.uid"
        >
          <div class="col code">
            <el-input v-model="m.code" placeholder="编码" />
          </div>
          <div class="col name">
            <el-input v-model="m.name" placeholder="名称" />
          </div>
          <div class="col dept">
            <el-tree-select
              v-model="m.deptId"
              :data="deptOptions"
              :props="{ value: 'id', label: 'label', children: 'children' }"
              check-strictly
              placeholder="部门"
            />
          </div>
          <div class="col area">
            <el-input v-model="m.area" placeholder="区域" />
          </div>
          <div class="col spec">
            <el-input v-model="m.specification" placeholder="规格" />
          </div>
          <div class="col brand">
            <el-input v-model="m.brand" placeholder="品牌" />
          </div>
          <div class="col amount">
            <el-input-number v-model="m.amount" :min="0" />
          </div>
  
          <!-- 备件信息 -->
          <div class="col spares">
            <el-button
              size="small"
              type="primary"
              @click="openSpareDialog(i)"
            >
              编辑({{ m.spares.length }})
            </el-button>
          </div>
  
          <!-- 操作列 -->
          <div class="col ops">
            <el-button link size="small" type="primary" @click="copyRow(i)">复制</el-button>
            <el-button link size="small" type="danger" @click="removeRow(i)">删除</el-button>
          </div>
        </div>
  
        <div class="add-btn">
          <el-button size="small" type="success" plain @click="addRow">＋ 新增一行</el-button>
        </div>
      </div>
  
      <!-- 子弹窗：备件信息编辑 -->
      <el-dialog
        v-model="spareDialog.visible"
        title="编辑备件信息"
        width="75%"
        append-to-body
      >
        <div class="spare-table">
          <div class="spare-header">
            <div class="col name">备件名称</div>
            <div class="col vendor">厂商</div>
            <div class="col spec">规格</div>
            <div class="col qty">数量</div>
            <div class="col ops">操作</div>
          </div>
  
          <div
            v-for="(sr, j) in spareDialog.spares"
            :key="sr.uid"
            class="spare-row"
          >
            <div class="col name">
              <el-select-v2
                v-model="sr.spareId"
                :options="spareList"
                placeholder="请选择备件"
                filterable
                clearable
                @change="loadVendors(j)"
              />
            </div>
            <div class="col vendor">
              <el-select-v2
                v-model="sr.vendor"
                :options="sr.vendorOptions"
                placeholder="选择厂商"
                :disabled="!sr.spareId"
                @change="loadSpecs(j)"
              />
            </div>
            <div class="col spec">
              <el-select-v2
                v-model="sr.spec"
                :options="sr.specOptions"
                placeholder="选择规格"
                :disabled="!sr.vendor"
              />
            </div>
            <div class="col qty">
              <el-input-number v-model="sr.qty_need" :min="1" />
            </div>
            <div class="col ops">
              <el-button link size="small" @click="copySpare(j)">复制</el-button>
              <el-button link size="small" type="danger" @click="removeSpare(j)">删除</el-button>
            </div>
          </div>
  
          <div class="add-btn">
            <el-button size="small" type="success" plain @click="addSpare">＋ 新增一行</el-button>
          </div>
        </div>
  
        <template #footer>
          <el-button @click="spareDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="saveSpares">确定</el-button>
        </template>
      </el-dialog>
  
      <template #footer>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="submit">创建</el-button>
      </template>
    </el-dialog>
  </template>
<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { cascaderChildren, createMachines } from "@/api/sbtz/sbtz";
import { listSpare, getVendorsBySpare, getSpecsBySpareVendor } from "@/api/sbtz/spare";
import { deptTreeSelect } from "@/api/system/user";
import AddSpareDialog  from "@/components/sbtz/spare/AddSpareDialog.vue";

const visible = ref(false);
const loading = ref(false);

// 系统选择
const rootPath = ref([]);
const selectedSystemId = ref(null);
const cProps = {
  checkStrictly: true,
  emitPath: true,
  value: "id",
  label: "label",
  lazy: true,
  lazyLoad: async (node, resolve) => {
    const parentId = node.level === 0 ? 0 : node.value;
    const res = await cascaderChildren(parentId);
    let list = res?.data || [];
    if (node.level === 0)
      list = list.filter((x) => (x.nodeType || x.node_type) === "SYSTEM");
    resolve(list);
  },
};
function onSystemSelect(val) {
  if (val?.length) {
    selectedSystemId.value = val[val.length - 1];
  } else {
    selectedSystemId.value = null;
  }
}


const addDialog = ref(null);
function loadData() {
  console.log("刷新数据...");
}

// 部门 & 备件
const deptOptions = ref([]);
const spareList = ref([]);
async function getDeptTree() {
  const res = await deptTreeSelect();
  deptOptions.value = res?.data ?? [];
}
async function getSpareList() {
  const res = await listSpare();
  spareList.value = res?.rows?.map(({ id, name }) => ({
    value: id,
    label: name,
  })) ?? [];
}

// 母设备列表
const machines = reactive([]);
function addRow() {
  machines.push({
    uid: Math.random().toString(36).slice(2),
    code: "",
    name: "",
    deptId: null,
    area: "",
    brand: "",
    amount: 0,
    specification: "",
    spares: [],
  });
}
function copyRow(i) {
  const newRow = JSON.parse(JSON.stringify(machines[i]));
  newRow.uid = Math.random().toString(36).slice(2);
  machines.splice(i + 1, 0, newRow);
}
function removeRow(i) {
  machines.splice(i, 1);
}

// 备件编辑弹窗
const spareDialog = reactive({
  visible: false,
  index: null,
  spares: [],
});
function openSpareDialog(i) {
  spareDialog.index = i;
  spareDialog.spares = JSON.parse(JSON.stringify(machines[i].spares || []));
  if (!spareDialog.spares.length) addSpare();
  spareDialog.visible = true;
}
function addSpare() {
  spareDialog.spares.push({
    uid: Math.random().toString(36).slice(2),
    spareId: null,
    vendor: null,
    spec: null,
    qty_need: 1,
    vendorOptions: [],
    specOptions: [],
  });
}
function removeSpare(j) {
  spareDialog.spares.splice(j, 1);
}
function copySpare(j) {
  const newRow = JSON.parse(JSON.stringify(spareDialog.spares[j]));
  newRow.uid = Math.random().toString(36).slice(2);
  spareDialog.spares.splice(j + 1, 0, newRow);
}
async function loadVendors(j) {
  const sr = spareDialog.spares[j];
  sr.vendor = null;
  sr.spec = null;
  sr.specOptions = [];
  sr.vendorOptions = await getVendorsBySpare(sr.spareId);
}
async function loadSpecs(j) {
  const sr = spareDialog.spares[j];
  sr.spec = null;
  sr.specOptions = await getSpecsBySpareVendor(sr.spareId, sr.vendor);
}
function saveSpares() {
  machines[spareDialog.index].spares = JSON.parse(JSON.stringify(spareDialog.spares));
  spareDialog.visible = false;
}

// 提交
const emit = defineEmits(["refresh"]);
async function submit() {
  if (!selectedSystemId.value) return ElMessage.error("请选择系统节点");
  if (!machines.length) return ElMessage.error("请至少添加一个母设备");

  const payload = {
    startParentId: selectedSystemId.value,
    reuseCode: false,
    layers: machines.map((m) => ({
      nodeType: "MACHINE",
      name: m.name,
      code: m.code,
      deptId: m.deptId,
      area: m.area,
      brand: m.brand,
      amount: m.amount,
      specification: m.specification,
      spareRelations: m.spares.map((s) => ({
        spareId: s.spareId,
        vendor: s.vendor,
        spec: s.spec,
        qty_need: s.qty_need,
      })),
    })),
  };

  loading.value = true;
  try {
    const res = await createMachines(payload);
    if (res.code === 200) {
      ElMessage.success("母设备创建成功");
      visible.value = false;
      emit("refresh");
    } else {
      ElMessage.error(res.msg || "创建失败");
    }
  } finally {
    loading.value = false;
  }
}

onMounted(() => {
  getDeptTree();
  getSpareList();
});

const open = () => {
  visible.value = true;
  rootPath.value = [];
  machines.splice(0);
  addRow();
};
defineExpose({ open });
</script>
<style scoped>
.machine-table,
.spare-table {
  border: 1px solid #ebeef5;
  border-radius: 8px;
}
.table-header,
.table-row,
.spare-header,
.spare-row {
  display: grid;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
  padding: 6px 8px;
}
.table-header {
  background: #f5f7fa;
  font-weight: 500;
  grid-template-columns: 15% 15% 15% 10% 10% 10% 10% 10% 5%;
}
.table-row {
  grid-template-columns: 15% 15% 15% 10% 10% 10% 10% 10% 5%;
}
.spare-header,
.spare-row {
  grid-template-columns: 25% 25% 25% 15% 10%;
}
.col {
  padding: 4px;
}
.col.ops {
  text-align: center;
}
.add-btn {
  text-align: right;
  padding: 8px;
}
</style>
